package 堆;

public class 原地堆排序 {
    public static void main(String[] args) {
        int[] arr = {4,2,1,6,7,9,12,0};
        原地堆排序  o = new 原地堆排序();
        o.heapSort(arr);
        for (int i:arr
             ) {
            System.out.print(i + " ");
        }
    }

    public void heapSort(int[] arr){
        //先最大堆化
        for (int i = (arr.length - 1 - 1) / 2; i >= 0; i--) {
            siftDown(arr,i,arr.length);
        }
        //在进行堆排序
        for (int i = arr.length - 1; i > 0; i--) {
            swap(arr,0,i);
            siftDown(arr,0,i);
        }
    }

    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    private void siftDown(int[] arr, int i, int length) {
        while (2 * i + 1 < length){
            int j = (2 * i) + 1;
            if (j + 1 < length && arr[j+1] > arr[j]){
                j = j+1;
            }
            if (arr[i] > arr[j]){
                break;
            }else {
                swap(arr,i,j);
                i = j;
            }
        }
    }
}
